package com.heatup.apt.api.service.impl;

import com.alibaba.druid.util.*;
import com.heatup.apt.api.service.CouponService;
import com.heatup.apt.api.service.UserProductServiceService;
import com.heatup.apt.api.service.UserService;
import com.heatup.apt.common.constants.CouponConstants;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.common.dao.user.UserActivityRecordMapper;
import com.heatup.apt.common.util.CouponUtil;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.model.api.ApiResultModel;
import com.heatup.apt.model.api.coupon.CouponApiResultModel;
import com.heatup.apt.model.coupon.ActivityInfo;
import com.heatup.apt.model.coupon.CouponDetail;
import com.heatup.apt.model.coupon.CouponInfo;
import com.heatup.apt.model.order.VipPurchaseLog;
import com.heatup.apt.model.product.ProductService;
import com.heatup.apt.model.user.UserActivityRecord;
import com.heatup.apt.model.user.UserInfo;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import java.text.*;
import java.util.*;


/**
 * 优惠券业务实现类
 *
 * @author Earvin
 */
@Service("couponService")
public class CouponServiceImpl implements CouponService {
    private static final Logger logger = LoggerFactory.getLogger(CouponServiceImpl.class);

    @Autowired
    private CouponApiResultMapper couponApiResultMapper;
    @Autowired
    private CouponInfoMapper couponInfoMapper;
    @Autowired
    private CouponDetailMapper couponDetailMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private VipPurchaseLogMapper vipPurchaseLogMapper;
    @Autowired
    private UserProductServiceService userProductServiceService;
    @Autowired
    private ActivityInfoMapper activityInfoMapper;
    @Autowired
    private UserActivityRecordMapper userActivityRecordMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    /**
     * 获取用户优惠券列表
     */
    @Override
    public Map<String, Object> queryUserCouponList(Map<String, Object> paramsMap) {

        Map<String, Object> responseMap = new HashMap<>();
        if (paramsMap.containsKey("limit_physical_examination_course") && orderInfoMapper.queryPrivateBodyExaminationOrderLeftCountByToDay() <= 0
                || paramsMap.containsKey("limit_secret_experience_course") && orderInfoMapper.queryPrivateExperienceOrderLeftCountByToDay() <= 0) {
            //如果是体测/体验订单 当日免费/用券名额已满就直接不再返回券
        } else {
            List<CouponApiResultModel> couponApiResultModel = couponApiResultMapper.queryUserCouponListBy(paramsMap);
            responseMap.put("coupon_list", couponApiResultModel);
        }
        return responseMap;
    }

    //添加或兑换一张优惠券， 先判断条件，再insert or update.
    private Ret_ChangeType insertOrUpdateCouponDetailBy(CouponInfo couponInfo, Integer userId, CouponDetail couponDetail, boolean bInsert, Map<String, Object> retMap) {
        if (CouponConstants.CouponStatus_Online.equals(couponInfo.getCouponStatus())) {  //2表示上架中
            if (couponInfo.getMaxCount() != 0 && couponInfo.getGetedCount() >= couponInfo.getMaxCount()) { //已领满
                return Ret_ChangeType.Ret_IsMax;
            }
            Date currDate = DateUtils.getDateShort(new Date());
            if (couponInfo.getChangeMode() == 2) {//2表示限制兑换时间
                if (retMap != null) {
                    retMap.put("change_begin_date", DateUtils.toDateString(couponInfo.getChangeBeginDate()));
                    retMap.put("change_end_date", DateUtils.toDateString(couponInfo.getChangeEndDate()));
                }

                if (currDate.before(couponInfo.getChangeBeginDate())) {
                    return Ret_ChangeType.Ret_BeforeTime;  //该券还未到兑换时间
                } else if (currDate.after(couponInfo.getChangeEndDate())) {
                    return Ret_ChangeType.Ret_ExpiredTime;  //该券的兑换时间已过
                }
            }

            int isUsed = 0;            //默认未使用
            int isGeted = 1;        //插入一张固定口令券，1表示已领取
            Date useBeginDate = couponInfo.getUseBeginDate();  //默认：把生效时间从主表复制一份到detail表
            Date useEndDate = couponInfo.getUseEndDate();
            Date now = DateUtils.getDateShort(new Date());  //只取年月日
            UserInfo oldUserInfo = userService.getUserInfoById(userId);
            Map<String, Object> resultMap = null;
            Date vipStartDate = couponInfo.getUseBeginDate();
            Date vipEndDate = couponInfo.getUseEndDate();

            if (CouponConstants.CouponType_Vip.equals(couponInfo.getCouponType())) {   //檬会员资格
                if (CouponConstants.UseMode_Now.equals(couponInfo.getUseMode())) { //立即生效
                    if (couponInfo.getDayNum() > 0) {
                        //增加会员天数
                        resultMap = userService.addUserVipDayNum(userId, couponInfo.getDayNum());

                        useBeginDate = now;  //立即生效，则开始时间从现在开始算
                        Calendar ca = Calendar.getInstance();
                        ca.add(Calendar.DATE, couponInfo.getDayNum() - 1);//增加的天数  //减1是为了计算到正确的结束时间,如:2016-12-1到2016-12-1(1天有效）
                        useEndDate = DateUtils.getDateShort(ca.getTime());

                        isUsed = 1;  //置为已使用
                        if (retMap != null) {
                            retMap.put("coupon_type", CouponConstants.CouponType_Vip);
                            retMap.put("is_used", 1);
                        }

                    }
                } else if (CouponConstants.UseMode_LimitTime.equals(couponInfo.getUseMode()) && !now.before(useBeginDate)) {  //该檬会员资格券的使用时间已经开始了
                    int dayNum = 0;  //因为end时间存的是 2016-12-19 00:00:00, 但又需要19号是全员，所以需要加一天
                    try {
                        dayNum = DateUtils.getDays(useEndDate).intValue() + 1;
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (dayNum >= 0) {
                        resultMap = userService.addUserVipDayNum(userId, dayNum);

                        isUsed = 1;  //置为已使用
                        if (retMap != null) {
                            retMap.put("coupon_type", CouponConstants.CouponType_Vip);
                            retMap.put("is_used", 1);
                        }
                    }
                }

                if (resultMap != null) {
                    useBeginDate = (Date) resultMap.get("useBeginDate");
                    vipStartDate = useBeginDate;
                    vipEndDate = (Date) resultMap.get("useEndDate");
                    if (vipEndDate != null) {
                        useEndDate = DateUtils.AddDays(vipEndDate, -1);
                    }

                }

            } else if (CouponConstants.CouponType_Monthly_Team_Course.equals(couponInfo.getCouponType())) { //团课包月卡
                //这个模块的内容只处理立即生效和固定期限的开始日期在当前时间之前的数据，
                // 固定使用期限限制的，如果开始日期在当前日期之后，则需要定时任务处理。与檬会员一致
                if (CouponConstants.UseMode_Now.equals( couponInfo.getUseMode())) { //立即生效
                    if (couponInfo.getDayNum() > 0) {
                        //增加会员天数
                        //userService.addUserVipDayNum(userId, couponInfo.getDayNum());
                        resultMap = userProductServiceService.addUserMonthTeamCourseProductDays(userId, couponInfo.getDayNum(), Integer.valueOf(couponInfo.getLimitStore()));


                        useBeginDate = now;  //立即生效，则开始时间从现在开始算
                        Calendar ca = Calendar.getInstance();
                        ca.add(Calendar.DATE, couponInfo.getDayNum() - 1);//增加的天数  //减1是为了计算到正确的结束时间,如:2016-12-1到2016-12-1(1天有效）
                        useEndDate = DateUtils.getDateShort(ca.getTime());


                        isUsed = 1;  //置为已使用
                        if (retMap != null) {
                            retMap.put("coupon_type", CouponConstants.CouponType_Monthly_Team_Course);
                            retMap.put("is_used", 1);
                        }

                    }
                } else if (CouponConstants.UseMode_LimitTime.equals(couponInfo.getUseMode()) && !now.before(useBeginDate)) {  //该檬会员资格券的使用时间已经开始了
                    int dayNum = 0;  //因为end时间存的是 2016-12-19 00:00:00, 但又需要19号是全员，所以需要加一天
                    try {
                        dayNum = DateUtils.getDays(useEndDate).intValue() + 1;
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (dayNum >= 0) {
                        //userService.addUserVipDayNum(userId, dayNum);
                        resultMap = userProductServiceService.addUserMonthTeamCourseProductDays(userId, couponInfo.getDayNum(), Integer.valueOf(couponInfo.getLimitStore()));
                        isUsed = 1;  //置为已使用
                        if (retMap != null) {
                            retMap.put("coupon_type", CouponConstants.CouponType_Monthly_Team_Course);
                            retMap.put("is_used", 1);
                        }
                    }
                }

                if (resultMap != null) {
                    useBeginDate = (Date) resultMap.get("useBeginDate");
                    vipStartDate = useBeginDate;
                    vipEndDate = (Date) resultMap.get("useEndDate");
                    if (vipEndDate != null) {
                        useEndDate = DateUtils.AddDays(vipEndDate, -1);
                    }

                }
            } else { //现金券或折扣券或团课体验券
                if (CouponConstants.UseMode_Now == couponInfo.getUseMode()) { //立即生效: 从领取之日开始计算
                    if (couponInfo.getDayNum() > 0) {
                        useBeginDate = now;  //立即生效，则开始时间从现在开始算
                        Calendar ca = Calendar.getInstance();
                        ca.add(Calendar.DATE, couponInfo.getDayNum() - 1);//增加的天数
                        useEndDate = DateUtils.getDateShort(ca.getTime());
                    }
                }
            }

            if (retMap != null) {
                retMap.put("code_type", couponInfo.getCouponType());
            }

            //添加一条领取记录（固定口令：到这里必定是需要插入的，前面已经判断了是否领过）
            try {
                if (couponDetail == null) {
                    //首页判断是否存已经生成coupon_code，但在该批次未领取的券进行使用
                    couponDetail = couponDetailMapper.queryCouponCodeByCouponId(couponInfo.getId());
                    if (couponDetail == null) {
                        couponDetail = new CouponDetail();
                    } else {
                        bInsert = false;
                    }
                }
                couponDetail.setCouponId(couponInfo.getId());

                if (bInsert) {  //插入时才用重新生成兑换券
                    couponDetail.setCouponCode(generatorCouponCodeBy(couponInfo.getId()));
                    couponDetail.setMakeTime(new Date());
                }

                couponDetail.setIsGeted(isGeted);  //设为已领取
                if (isGeted == 1) {
                    couponDetail.setGetTime(new Date());
                }
                couponDetail.setUserId(userId);
                couponDetail.setIsUsed(isUsed); //设为未使用
                couponDetail.setUseBeginDate(useBeginDate);
                couponDetail.setUseEndDate(useEndDate);
                if (isUsed == 1) {
                    couponDetail.setUseTime(new Date());
                }

                if (bInsert == true) {
                    couponDetailMapper.insertSelective(couponDetail);
                    logger.info("======== insertOrUpdateCouponDetailBy insert======================= parameter : change_code=" + couponDetail.getCouponCode() + " userId =" + userId);

                } else {
                    couponDetailMapper.updateByPrimaryKeySelective(couponDetail);
                    logger.info("======== insertOrUpdateCouponDetailBy update======================= parameter : change_code=" + couponDetail.getCouponCode() + " userId =" + userId);
                }

                //如果是会员券兑换则，插入到vip_purchase_log表
                //modify by earvin 2017-05-16日志放入addUserVipDayNum再更新
                //写入新增会员日志
                if (CouponConstants.CouponType_Vip.equals( couponInfo.getCouponType()) && CouponConstants.UseMode_Now.equals( couponInfo.getUseMode())) {
                    this.saveVipPurchaseLog(userId, couponDetail.getId().intValue(), 3, 1, vipStartDate, vipEndDate);
                } else if (CouponConstants.CouponType_Monthly_Team_Course.equals( couponInfo.getCouponType()) && CouponConstants.UseMode_Now.equals( couponInfo.getUseMode())) {
                    ProductService productService = (ProductService) resultMap.get("productService");
                    if (productService != null) {
                        this.saveVipPurchaseLog(userId, couponDetail.getId().intValue(), 4, productService.getId().intValue(), vipStartDate, vipEndDate);
                    }
                }
                //券的领取人数加1
                couponInfo.setGetedCount(couponInfo.getGetedCount() + 1);
                couponInfoMapper.updateSelectiveById(couponInfo);

                return Ret_ChangeType.Ret_Success;

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("insertOrUpdateCouponDetailBy change_code=" + couponDetail.getCouponCode() + " userId =" + userId + " error log:" + e.getMessage());
                throw new RuntimeException();
            }
        }
        return Ret_ChangeType.Ret_InValid;
    }


    private void saveVipPurchaseLog(Integer userId, Integer orderId,
                                    int purchaseType, int productServiceId, Date vipStartDate, Date vipEndDate) {
        try {
            VipPurchaseLog vipLog = new VipPurchaseLog();
            vipLog.setUserId(userId);
            vipLog.setOrderId(orderId);
            vipLog.setPurchaseType(purchaseType);
            vipLog.setProductServiceId(productServiceId);
            vipLog.setStartTime(vipStartDate);
            vipLog.setEndTime(vipEndDate);
            vipLog.setCreatedTime(new Date());
            vipLog.setLevel(2);
            vipPurchaseLogMapper.insertSelective(vipLog);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("兑换优惠券时插入会员日志出错: ===>> ", e.getMessage());
        }
    }


    //领取(添加)优惠券 该接口主要给活动用. canRepeat: true表示同一张优惠券，可以领多次。
    @Override
    public Ret_ChangeType addCouponDetail(Integer couponId, Integer userId, boolean canRepeat) {
        logger.info("======== addCouponDetail insert======================= parameter : couponId=" + couponId + " userId =" + userId);

        //先查询是否有该优惠券
        CouponInfo couponInfo = couponInfoMapper.selectById(couponId);
        if (couponInfo == null) {
            return Ret_ChangeType.Ret_NotFound; //表示没有该兑换券
        }

        if (couponInfo.getCouponStatus() != CouponConstants.CouponStatus_Online) {
            return Ret_ChangeType.Ret_InValid;  //该优惠券已下架
        }

        if (canRepeat == false) {
            //查Detail表里，此优惠券该用户是否已领过
            CouponDetail couponDetail = couponDetailMapper.selectByCouponId(couponId, userId);
            if (couponDetail != null && couponDetail.getUserId().intValue() == userId) {
                return Ret_ChangeType.Ret_AlreadyChange; //该券已领取
            }
        }

        //插入一条优惠券
        return insertOrUpdateCouponDetailBy(couponInfo, userId, null, true, null);
    }

    //------------------------------------------------------------------------
    //兑换优惠券
    private Ret_ChangeType changeCoupon(String change_code, Integer userId, Map<String, Object> retMap) {
        logger.info("======== changeCoupon start ======================= parameter : change_code=" + change_code + " userId =" + userId);

        if (StringUtils.isEmpty(change_code) || userId < 1) {
            return Ret_ChangeType.Ret_Other;
        }
        //先查询是否有该优惠券 --固定的口令是在coupon_info表
        CouponInfo couponInfo = couponInfoMapper.selectByCouponCode(change_code);
        if (couponInfo == null) {
            //如果主表查不到，一定是随机产生的兑换券，查coupon_detail表
            CouponDetail couponDetail = couponDetailMapper.selectByCouponCode(change_code);

            if (couponDetail == null) {
                //coupon_info和coupon_detail表都查不到，则表示没有该兑换券
                return Ret_ChangeType.Ret_NotFound;
            } else {
                //一定是随机生成的兑换码。并且是已经在detail表里面有的，这里最多只用update状态
                if (0 == couponDetail.getIsValid()) {
                    //该优惠券已失效
                    return Ret_ChangeType.Ret_InValid;
                } else if (1 == couponDetail.getIsGeted()) {
                    //该券已领取
                    return Ret_ChangeType.Ret_AlreadyChange;
                } else {
                    //先查询coupon_info表，取兑换时间等参数比较
                    couponInfo = couponInfoMapper.selectById(couponDetail.getCouponId());
                    if (couponInfo == null) {
                        return Ret_ChangeType.Ret_NotFound;
                    } else if (couponInfo.getGetMode() == 1) { //到这里的话，mode必须是随机生成，这里强校验下。
                        return Ret_ChangeType.Ret_NotFound;
                    } else if (couponInfo.getIsOneVote() == 1) {
                        //如果优惠券批次有关于兑换次数限制，一个用户只能在该批次兑换一次
                        CouponDetail changeCouponDetail = couponDetailMapper.selectByCouponId(couponInfo.getId(), userId);
                        if (changeCouponDetail != null) {
                            //如果已存在优惠券信息，则表示该用户已兑换过该批次优惠券。
                            return Ret_ChangeType.Ret_Exchanged;
                        }
                    }
                    //插入一条优惠券
                    return insertOrUpdateCouponDetailBy(couponInfo, userId, couponDetail, false, retMap);
                }
            }

        } else {
            //固定的口令，只在coupon_info表里有，Detail表里可能会有领取记录（有则表示添加过，没有则添加)
            CouponDetail couponDetail = couponDetailMapper.selectByCouponCodeUserID(change_code, userId);
            if (couponDetail != null && couponDetail.getCouponId().intValue() == couponInfo.getId().intValue() && userId.intValue() == couponDetail.getUserId().intValue()) {//口令相同，并且批次相同， 则表示已经领取
                //该券已领取
                return Ret_ChangeType.Ret_AlreadyChange;
            }

            //插入一条优惠券
            return insertOrUpdateCouponDetailBy(couponInfo, userId, couponDetail, true, retMap);
        }
    }

    /**
     * 兑换优惠券，如果兑换成功，直接返回用户优惠券列表
     */
    @Override
    public ApiResultModel changeCoupon(Map<String, Object> paramsMap) {
        ApiResultModel model = new ApiResultModel();

        Map<String, Object> retMap = new HashMap<String, Object>();//返回的参数，前端需要根据这些参数做相应的动作。比如：立即生效的檬会员体验券，需要跳到已使用
        Ret_ChangeType retType = changeCoupon(paramsMap.get("change_code").toString(), Integer.valueOf(paramsMap.get("user_id").toString()), retMap);
        if (retType == Ret_ChangeType.Ret_Success) {

            Map<String, Object> responseMap = new HashMap<String, Object>();
            List<CouponApiResultModel> couponApiResultModel = couponApiResultMapper.queryUserCouponListBy(paramsMap);
            responseMap.put("coupon_list", couponApiResultModel);
            responseMap.put("isSubScribe", userService.isSubScribe(paramsMap.get("user_id").toString()));
            responseMap.putAll(retMap);

            model.setData(responseMap);
        }

        model.setRet(retType.getIndex());
        model.setErrorCode(retType.getIndex());
        if (retType == Ret_ChangeType.Ret_BeforeTime && retMap.get("change_begin_date") != null) {
            model.setMsg("温馨提示：该券的兑换时间还没到，兑换开始时间为：" + retMap.get("change_begin_date"));
        } else if (retType == Ret_ChangeType.Ret_ExpiredTime && retMap.get("change_end_date") != null) {
            model.setMsg("温馨提示：该券的兑换时间已过，兑换结束时间为：" + retMap.get("change_end_date"));
        } else {
            model.setMsg(retType.getValue());
        }

        return model;
    }


    /**
     * 按照批次信息生成兑换码,如果获取方式是1：用户输入码，则直接使用couponInfo里面的兑换码；
     * 如果兑换方式为2：系统自动生成：兑换码==4位批次+12位不重复的字符串组合。保证唯一性。
     *
     * @param couponId 兑换券批次ID
     * @return String couponCode 兑换码
     */
    @Override
    public String generatorCouponCodeBy(Integer couponId) {
        CouponInfo couponInfo = couponInfoMapper.queryById(couponId);
        if (couponInfo != null) {
            // 如果获取方式是用户输入兑换码领取，表示兑换码已固定，否则则生成兑换码
            if (1 == couponInfo.getGetMode().intValue()) {
                return couponInfo.getCouponCode();
            } else {
                String couponCode = null;
                // 从数据库查询出是否存在兑换码，如果有则从新生成。
                while (true) {
                    couponCode = CouponUtil.generatorCoupinCode(couponId);
                    CouponDetail couponDetail = couponDetailMapper.selectByCouponCode(couponCode);
                    if (couponDetail == null) {
                        break;
                    }
                }
                return couponCode;
            }
        } else {
            return null;
        }
    }

    /**
     * 邀请者和被邀请者可获得优惠券
     */
    @Override
    public Ret_ChangeType addCouponDetailByActivityId(Integer activity_id, Integer userId) {
        logger.info("======== create CouponDetail By ActivityId start ======================= parameter : activity_id=" + activity_id + " userId =" + userId);
        // 根据活动id查询优惠券
        ActivityInfo activityInfo = activityInfoMapper.selectById(activity_id);
        if (activityInfo == null) {
            logger.info("========select activityInfo is null ");
            return Ret_ChangeType.Ret_NotFound;
        }
        String couponIdStrs = activityInfo.getInviteCouponId();
        Ret_ChangeType ret = null;
        // 这里有可能会有多个优惠券
        String couponIdStr[] = couponIdStrs.split("#");
        logger.info("========couponIdStr :" + Arrays.toString(couponIdStr) + "=========================");
        if (couponIdStrs.indexOf("#") > 0) {
            for (String str : couponIdStr) {
                int couponId = Integer.valueOf(str);
                ret = addCouponDetail(couponId, userId, false);
                logger.info("======== for ret :index" + ret.getIndex() + " value:" + ret.getValue() + "=couponId:" + couponId + "========================");

            }
        } else {
            int couponId = Integer.valueOf(couponIdStrs);
            ret = addCouponDetail(couponId, userId, false);
            logger.info("========  ret :index" + ret.getIndex() + " value:" + ret.getValue() + "==couponId1:" + couponId + "=======================");
        }
        return ret;

    }

    /**
     * 根据优惠券批次ID 查询优惠券兑换码
     */
    @Override
    public ApiResultModel queryCouponCodeByCouponId(Integer couponId) {
        ApiResultModel model = new ApiResultModel();
        if (couponId > 0) {
            CouponDetail couponDetail = couponDetailMapper.queryCouponCodeByCouponId(couponId);
            if (couponDetail != null) {
                model.setData(couponDetail);
                model.setRet(ApiResultModel.RET_SUCCESS);
            } else {
                model.setRet(ApiResultModel.RET_SUCCESS);
                model.setMsg("该批次的优惠券已兑换完");
            }
        } else {
            model.setRet(ApiResultModel.RET_ERROR);
            model.setMsg("未传入正确参数");
        }
        return model;
    }

    /**
     * 赠送私教优惠券活动
     *
     * @param userId
     * @param activityInfo
     * @return
     */
    public Ret_ChangeType freeSecretCouponActivity(Integer  userId, ActivityInfo activityInfo) {

        // 1.用户是否有该批次的优惠券，如果有的话，则不赠送。
        // 2.根据批次信息生成优惠券给到该用户
        // 3.该批次的优惠券是否系统生成的，并且未限制数量，并且是支持私教体验券和私教体测券。
        // 4.用户根据批次ID，来生成couponDetail信息，并且领取券。返回成功信息给到用户。
        //ActivityInfo activityInfo = activityInfoMapper.selectById(activityId);
        if (activityInfo == null || "0".equals(activityInfo.getStatus())) {
            logger.info("========freeSecretCouponActivity select activityInfo is null ");
            return Ret_ChangeType.Ret_NotFound;
        }
        //获取活动关联的批次信息
        String[] couponIds = activityInfo.getCouponId().split("#");
        Map<String, Object> param = new HashMap();
        param.put("user_id", userId);
        Ret_ChangeType ret = null;
        if (couponIds != null && couponIds.length > 0) {
            //如果所属活动的所有批次中拥有，则表示该用户已获得过该批次的优惠券，则不送其他的。
            param.put("coupons", couponIds);
            List<CouponApiResultModel> list = couponApiResultMapper.queryUserCouponListBy(param);
            if (list != null && list.size() > 0) {
                //表示已送过批次的券
                return Ret_ChangeType.Ret_Exchanged;
            }
            //兑换券
            for (String couponId : couponIds) {
                ret = addCouponDetail(Integer.valueOf(couponId), userId, false);
            }
            return ret;
        } else {
            return Ret_ChangeType.Ret_NotFound;
        }
    }

    /**
     * 判断是否推送活动通知
     * @param userId
     * @param activityId
     * @return pushFlag 0：表示不推送 1：推送1的标识 2：推送2的标志
     * 根据优惠券活动配置的ID来排序的，首页排的第一位则优先推送通知。
     */
    public Map<String, Object> freeFristCouponActivity(Integer userId, Integer activityId) {
        Map<String, Object> resp = new HashMap<>();

        ActivityInfo activityInfo = activityInfoMapper.selectById(activityId);
        Integer hasPushFlag = 0;
        //活动信息不为空
        if(activityInfo!=null){
            //是否有关于此批次的优惠券
            Ret_ChangeType ret = this.freeSecretCouponActivity(userId, activityInfo);
            if (Ret_ChangeType.Ret_Success.getIndex() == ret.getIndex() || Ret_ChangeType.Ret_Exchanged.getIndex() == ret.getIndex()) {
                String[] couponIds = activityInfo.getCouponId().split("#");
                if(couponIds !=null && couponIds.length>0){
                    for(int i=0;i<couponIds.length;i++){
                        Map<String,Object> paramMap = new HashMap();
                        paramMap.put("userId",userId);
                        paramMap.put("couponId",Integer.valueOf(couponIds[i]));
                        //查询用户是否拥有该优惠券，并且未使用
                        int couponDetailCount = couponDetailMapper.queryCouponUnUsedCount(paramMap);
                        UserActivityRecord entity = new UserActivityRecord();
                        entity.setUserId(userId);
                        entity.setActivityId(activityId);
                        entity.setCouponId(Integer.valueOf(couponIds[i]));
                        entity.setPushFlag("1");
                        UserActivityRecord record = userActivityRecordMapper.selectOne(entity);
                        if(record == null && couponDetailCount > 0){
                            hasPushFlag = i+1;
                            entity.setCreatedTime(new Date());
                            entity.setUpdatedTime(new Date());
                            userActivityRecordMapper.insert(entity);
                            break;
                        }
                    }
                }
            }
        }
        //如果兑换成功或者已兑换，则需要查询是否有推送消息记录。
        resp.put("pushFlag",hasPushFlag);
        return resp;
    }
}
